import React, {
  Component,
  useContext,
  useState,
  useEffect,
  useRef,
} from "react";
import { NavLink,Route,Switch } from "react-router-dom";
import { Container } from "./style";
import {
  DatePicker,
  Space,
  Select,
  Input,
  Button,
  Table,
  Popconfirm,
  Form,
  Pagination,
  Modal,
} from "antd";
import Draggable from "react-draggable";
import "antd/dist/antd.css";
import "moment/locale/zh-cn";
import locale from "antd/es/date-picker/locale/zh_CN";
import connect from "./connect";
import { PlusOutlined } from '@ant-design/icons';
import store from '../../store'
import { actionDelete } from "../../store/action/instorageAction";
import Instore from './Instore'
// 入库单
// import Instore from './Instore'
// 查看
import TakeInOfStorageForm from "./TakeInOfStorageForm";

import axios from "axios";
const { RangePicker } = DatePicker;
const { Option } = Select;
const EditableContext = React.createContext();

// 表格的事件
const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef();
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };

  // const save = async (e) => {
  //   try {
  //     const values = await form.validateFields();
  //     toggleEdit();
  //     handleSave({ ...record, ...values });
  //   } catch (errInfo) {
  //     console.log("Save failed:", errInfo);
  //   }
  // };

  let childNode = children;

  // if (editable) {
  //   childNode = editing ? (
  //     <Form.Item
  //       style={{
  //         margin: 0,
  //         width: 50,
  //       }}
  //       name={dataIndex}
  //       rules={[
  //         {
  //           required: true,
  //           message: `${title} is required.`,
  //         },
  //       ]}
  //     >
  //       <Input ref={inputRef} onPressEnter={save} onBlur={save} />
  //     </Form.Item>
  //   ) : (
  //     <div
  //       className="editable-cell-value-wrap"
  //       style={{
  //         width: 100,
  //       }}
  //       onClick={toggleEdit}
  //     >
  //       {children}
  //     </div>
  //   );
  // }

  return <td {...restProps}>{childNode}</td>;
};
@connect
class index extends Component {
  state = {
    // 时间组件的数据
    data: [],
    value: undefined,
    // 点击查看按钮的数据
    visible: false,
    disabled: true,
    // 分页器数据
    data: [],
    pagination: {
      current: 1,
      pageSize: 10,
    },
    loading: false,
  };
  componentDidMount() {
    // 在这里发送每个页面获取数据的请求
    this.props.setStorageData();
    // let ret = axios.get('http://localhost:9090/instorage')
  }

  // 选择器的事件
  onChange = (value) => {
    console.log(`selected ${value}`);
  };

  onBlur = () => {
    console.log("blur");
  };

  onFocus = () => {
    console.log("focus");
  };

  onSearch = (val) => {
    console.log("search:", val);
  };

  // 点击查看时候的事件
  state = {
    visible: false,
    disabled: true,
  };

  showModal = () => {
    this.setState({
      visible: true,
    });
  };

  handleOk = (e) => {
    console.log(e);
    this.setState({
      visible: false,
    });
  };

  handleCancel = (e) => {
    console.log(e);
    this.setState({
      visible: false,
    });
  };

  constructor(props) {
    super(props);
    this.columns = [
      {
        title: "序号",
        dataIndex: "key",
        editable: true,
      },
      {
        title: "入库单号",
        dataIndex: "innum",
      },
      {
        title: "入库日期",
        dataIndex: "indate",
      },
      {
        title: "入库类型",
        dataIndex: "intype",
      },
      {
        title: "入库仓库",
        dataIndex: "instorage",
      },
      {
        title: "供应商",
        dataIndex: "itemsupplier",
      },
      {
        title: "物品数量",
        dataIndex: "itemnum",
      },
      {
        title: "制单人",
        dataIndex: "makeman",
      },
      {
        title: "制单日期",
        dataIndex: "makedate",
      },
      {
        title: "操作",
        dataIndex: "operation",
        render: (text, record) => (
          <div>
            {/* 查看事件 */}
            <a onClick={this.showModal}> 查看 &nbsp;&nbsp;</a>
            <Modal
              title={
                <div
                  style={{
                    width: "100%",
                    cursor: "move",
                  }}
                  onMouseOver={() => {
                    if (this.state.disabled) {
                      this.setState({
                        disabled: false,
                      });
                    }
                  }}
                  onMouseOut={() => {
                    this.setState({
                      disabled: true,
                    });
                  }}
                  onFocus={() => {}}
                  onBlur={() => {}}
                  // end
                >
                  <span>查看入库单</span>
                </div>
              }
              visible={this.state.visible}
              onOk={this.handleOk}
              mask={true}
              width={1000}
              maskStyle={{ opacity: 0.1 }}
              onCancel={this.handleCancel}
              okText="确认"
              cancelText="取消"
              modalRender={(modal) => <Draggable>{modal}</Draggable>}
            >
              <TakeInOfStorageForm />
            </Modal>

            {/* 修改事件 */}
            <NavLink activeClassName="top" to="">
              修改&nbsp;&nbsp;
            </NavLink>
            {/* 删除事件 */}
            <Popconfirm
              title="确认删除吗?"
              onConfirm={() => this.handleDelete(record.key)}
            >
              <a> 删除 </a>
            </Popconfirm>
          </div>
        ),
      },
    ];
    this.state = {
      // instorage: [],
      //   dataSource: [
      //     {
      //       key: "0",
      //       name: "1",
      //       innum: "bk200220201225",
      //       indate: "2020-12-25",
      //       intype: "采购入库",
      //       instorage: "北科二班11号仓库303房间",
      //       itemsupplier: "张俊",
      //       itemnum: "5",
      //       makeman: "秦始皇",
      //       makedate: "2020-12-25",
      //     },
      //     {
      //       key: "1",
      //       name: "2",
      //       innum: "bk200220201226",
      //       indate: "2020-12-26",
      //       intype: "采购入库",
      //       instorage: "北科一班",
      //       itemsupplier: "熊熊熊",
      //       itemnum: "4",
      //       makeman: "秦始皇",
      //       makedate: "2020-12-25",
      //     },
      //   ],
      //   count: 2,
    };
  }

  // 删除事件
  handleDelete = (key) => {
    const instorage = [...this.props.instorage];

    // this.setState({
    //   instorage: instorage.filter((item) => {
    //     item.key !== key
    //     console.log("item",item,"key")
    //   }),
    //   // instorage: instorage.pop(),
      
    // });


    var newdata= instorage.filter((item) => {
      return item.key != key
    })
    store.dispatch({type:'deleteStorageData',
    data:newdata})
  };

  handleSave = (row) => {
    const newData = [...this.state.dataSource];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, { ...item, ...row });
    this.setState({
      dataSource: newData,
    });
  };

  // 查询事件
  search = () => {
    // console.log(this.state)
  };

  render() {
    // console.log(this.props.instorage.data);
    // this.setState({instorage:this.props.instorage.data})
    // 表格事件

    const { instorage } = this.state;
    const components = {
      body: {
        row: EditableRow,
        cell: EditableCell,
      },
    };
    const columns = this.columns.map((col) => {
      if (!col.editable) {
        return col;
      }

      return {
        ...col,
        onCell: (record) => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <Container>
        {/* 主体 */}
        <div className="mainWrap">
          <div className="main">
            {/* 内容区 */}
            <div className="content">
              {/* 头部查询 */}
              <div className="title">
                {/* logo */}
                <NavLink activeClassName="top" className="top1" to="/management/instore">
                  <i><PlusOutlined /></i>
                  <span>入库单</span>
                </NavLink>
                
                {/* 时间组件 */}
                <div className="time">
                  <Space direction="vertical" size={12}>
                    <RangePicker
                      locale={locale}
                      style={{
                        width: 220,
                        height: 36,
                        borderRadius: 3,
                        marginLeft: 70,
                      }}
                    />
                  </Space>
                </div>
                {/* 全部入库类型组件 */}
                <div className="allTypes">
                  <Select
                    showSearch
                    defaultValue="all"
                    style={{
                      width: 150,
                      height: 36,
                      borderRadius: 3,
                      marginLeft: 10,
                    }}
                    placeholder="Select a person"
                    optionFilterProp="children"
                    onChange={this.onChange}
                    onFocus={this.onFocus}
                    onBlur={this.onBlur}
                    onSearch={this.onSearch}
                    filterOption={(input, option) =>
                      option.children
                        .toLowerCase()
                        .indexOf(input.toLowerCase()) >= 0
                    }
                  >
                    <Option value="all">全部入库类型</Option>
                    <Option value="buy">采购入库</Option>
                    <Option value="inventory">盘盈</Option>
                    <Option value="other">其他</Option>
                  </Select>
                </div>
                {/* 全部入库仓库组件 */}
                <div className="allWarehousing">
                  <Select
                    showSearch
                    defaultValue="all"
                    style={{
                      width: 240,
                      height: 36,
                      borderRadius: 3,
                      marginLeft: 10,
                    }}
                    placeholder="Select a person"
                    optionFilterProp="children"
                    onChange={this.onChange}
                    onFocus={this.onFocus}
                    onBlur={this.onBlur}
                    onSearch={this.onSearch}
                    filterOption={(input, option) =>
                      option.children
                        .toLowerCase()
                        .indexOf(input.toLowerCase()) >= 0
                    }
                  >
                    <Option value="all">全部入库仓库</Option>
                    <Option value="mySchool">
                      陈经纶中学本部高中-行政楼1号仓库
                    </Option>
                    <Option value="syStorage">
                      陈经纶中学本部高中-实验耗材仓库
                    </Option>
                    <Option value="jmStorage">
                      陈经纶中学嘉明分校-嘉明仓库
                    </Option>
                    <Option value="djSchool">
                      陈经纶中学帝景分校-行政楼1号仓库
                    </Option>
                  </Select>
                </div>
                {/* 全部供应商组件 */}
                <div className="allSuppliers">
                  <Select
                    showSearch
                    style={{
                      width: 150,
                      height: 36,
                      borderRadius: 3,
                      marginLeft: 10,
                    }}
                    placeholder="Select a person"
                    optionFilterProp="children"
                    onChange={this.onChange}
                    onFocus={this.onFocus}
                    onBlur={this.onBlur}
                    onSearch={this.onSearch}
                    defaultValue="all"
                    filterOption={(input, option) =>
                      option.children
                        .toLowerCase()
                        .indexOf(input.toLowerCase()) >= 0
                    }
                  >
                    <Option value="all">全部供应商</Option>
                    <Option value="jd">京东商城</Option>
                    <Option value="jwx">金五星批发市场</Option>
                    <Option value="xm">小米有品</Option>
                  </Select>
                </div>
                {/* 入库单号 */}
                <div className="entryNum">
                  <Input
                    placeholder="入库单号"
                    style={{
                      width: 120,
                      height: 36,
                      borderRadius: 3,
                      marginLeft: 10,
                    }}
                  />
                </div>
                {/* 查询按钮 */}
                <Button type="primary" className="button" onClick={this.search}>
                  查询
                </Button>
              </div>

              {/* 表格 */}
              {this.props.instorage ? (
                <div className="table">
                  <Table
                    components={components}
                    rowClassName={() => "editable-row"}
                    bordered
                    dataSource={this.props.instorage}
                    columns={columns}
                    // pagination={pagination}
                  />
                </div>
              ) : (
                ""
              )}

              {/* <Pagination
                total={85}
                showSizeChanger
                showQuickJumper
                showTotal={(total) => `Total ${total} items`}
              /> */}
              {/* 分页 */}
            </div>
          </div>
        </div>




        <Switch>
          <Route path="/management/instore" component={Instore} />
        </Switch>
      </Container>
    );
  }
}

export default index;
